#!/bin/bash
# Author: oldboy linux34 chentiangang ivan
# The script calls the function library.

check(){
  if [ $? == 0 ];then
    echo "SUCCESS."
  else
    echo "ERROR."
    exit 1
  fi
}

create_key(){
  user_key_file=${user_home}/.ssh/id_rsa
  if ! [ -f ${user_key_file} ];then
    echo "INFO: 生成本地密钥"
    mkdir -p ${user_home}/.ssh
    ssh-keygen -P '' -f ${user_key_file} &> /dev/null
    check
    chown -R ${username}.${username} $user_home
  fi
}

add_user(){
  if ssh -i ${user_key_file} -p${ssh_port} ${username}@${IP} "id ${username}" &> /dev/null;then
    echo "远端用户已存在"
    exit 1
  else
    echo "INFO: 创建远端用户"
    #ansible $IP -m shell -a "useradd ${username} && mkdir -p ${user_home}/.ssh" &>/dev/null
    ssh -l root ${IP} "useradd ${username} && mkdir -p ${user_home}/.ssh" &>/dev/null
    check
  fi
}

send_key(){
  echo "INFO: 发送公钥到远程主机" 
  if [ ${username} == "root" ];then
      echo "username: "${username}
      ssh-copy-id -i ${user_key_file}.pub -p ${ssh_port}  ${username}@${IP} &>/dev/null
      check
  else
      scp -P${ssh_port}  ${user_key_file}.pub root@${IP}:${user_home}/.ssh/authorized_keys &>/dev/null
      check
  fi
  echo "INFO: 修改权限"
  ssh -l root ${IP} "chmod 600 ${user_home}/.ssh/authorized_keys && chown -R ${username}.${username} ${user_home}" &>/dev/null
  check
}

randstr() {
  index=0
  str=""
  for i in {a..z}; do arr[index]=$i; index=`expr ${index} + 1`; done
  for i in {A..Z}; do arr[index]=$i; index=`expr ${index} + 1`; done
  for i in {0..9}; do arr[index]=$i; index=`expr ${index} + 1`; done
  for i in {1..20}; do str="$str${arr[$RANDOM%$index]}"; done
  echo $str
}
